//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2005
//
// Map view position handling.
//

# include "StdAfx.h"
# include "Position.h"
# include "Scale.h"
# include "Map.h"
# include "MapView.h"
# include "COMViewEvents.h"
# include "fast_floor.h"

	// Size of the window in pixels.
long g_lWidth = 0, g_lHeight = 0;
	// Size of the map in pixels.
long g_lMapWidth, g_lMapHeight;

	// Shift of the window in degrees.
float g_X, g_Y;
	// Shift of the window in pixels.
long g_lX, g_lY;

long XToScreen (float _x) {return                 fast_floor (.5f + g_kX*(_x - g_map.rectBound.x0 - g_X));}
long YToScreen (float _y) {return g_lHeight - 1 - fast_floor (.5f + g_kY*(_y - g_map.rectBound.y0 - g_Y));}

void ScreenToPt (int _x, int _y, point_t & _point) {
	_point.x = g_map.rectBound.x0 + g_X + _x/g_kX;
	_point.y = g_map.rectBound.y0 + g_Y + (g_lHeight - 1 - _y)/g_kY;
}

void GetVisibleRect (rect_t & _rectVisible) {
	CCritSec::CLock lock (g_cs);

	_rectVisible.x0 = g_map.rectBound.x0 + g_X;
	_rectVisible.y0 = g_map.rectBound.y0 + g_Y;
	_rectVisible.x1 = _rectVisible.x0 + g_lWidth/g_kX;
	_rectVisible.y1 = _rectVisible.y0 + g_lHeight/g_kY;
}

void SetPosition (long _lX, long _lY) {
	if (_lX != g_lX) {
		if (g_lWidth <= g_lMapWidth) {
			if (_lX < -c_iMargin)
				_lX = -c_iMargin;
			if (_lX > g_lMapWidth + c_iMargin - g_lWidth)
				_lX = g_lMapWidth + c_iMargin - g_lWidth - 1;
		} else {
			// TODO:
		}

		g_lX = _lX;
		g_X = g_lX/g_kX;
	}

	if (_lY != g_lY) {
		if (g_lHeight <= g_lMapHeight) {
			if (_lY < -c_iMargin)
				_lY = -c_iMargin;
			if (_lY > g_lMapHeight + c_iMargin - g_lHeight)
				_lY = g_lMapHeight + c_iMargin - g_lHeight - 1;
		} else {
			// TODO:
		}

		g_lY = _lY;
		g_Y = g_lY/g_kY;
	}

	Fire_OnPositionChange ();
}

void SetToCenter (const point_t & _point) {
	CCritSec::CLock lock (g_cs);

	g_X = _point.x - g_map.rectBound.x0 - .5f*g_lWidth/g_kX;
	g_Y = _point.y - g_map.rectBound.y0 - .5f*g_lHeight/g_kY;

	g_lX = fast_floor (g_X*g_kX + .5f);
	g_lY = fast_floor (g_Y*g_kY + .5f);

	Fire_OnPositionChange ();
}
